using System;
using System.IO;
using BSDS.Core.Infrastructure.Logging;

namespace BSDS.Core.Data.TemporaryFiles
{
    public class TempFolderManager : IDisposable
    {
        private bool initialized;

        private readonly Logger logger;
        private readonly string tempFolderName;
        private readonly bool removeTempFolderOnExit;

        public TempFolderManager(Logger logger, string tempFolderName, bool removeTempFolderOnExit)
        {
            this.logger = logger;
            this.tempFolderName = tempFolderName;
            this.removeTempFolderOnExit = removeTempFolderOnExit;
        }

        public void Intialize()
        {
            if(!Directory.Exists(tempFolderName))
            {
                Directory.CreateDirectory(tempFolderName);
            }

            initialized = true;
        }


        public void CleanUpFiles()
        {
            if (Directory.Exists(tempFolderName))
            {
                foreach (var file in Directory.GetFiles(tempFolderName))
                {
                    File.Delete(file);
                }
            }
        }

        public void Dispose()
        {
            if(removeTempFolderOnExit && initialized)
            {
                try
                {
                    Directory.Delete(tempFolderName, true);
                }
                catch(Exception e)
                {
                    logger.Log("Cannot delete temp folder. Error: " + e.Message);
                }
            }
        }
    }
}